/*
 * @Author: 0x9DEFA478
 * @Date: 2025-10-03 20:49:13
 * @LastEditTime: 2025-10-04 16:03:45
 * @LastEditors: 0x9DEFA478
 * @Description: 
 * 
 */
#include "./Error.hpp"




namespace SystemAPI{

  namespace Windows{

#if defined(_WIN32)

    std::string GetErrorString(DWORD error)noexcept{
      LPWSTR system_arr=nullptr;
      char* utf8_arr=nullptr;
      std::string r;

      do{
        FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,nullptr,error,LANG_USER_DEFAULT,(LPWSTR)&system_arr,0,nullptr);
        
        if(system_arr==nullptr){
          r="<获取失败>";
          break;
        }

        int res=WideCharToMultiByte(CP_UTF8,0,system_arr,-1,nullptr,0,nullptr,nullptr);
        if(res<1){
          r="<获取失败>";
          break;
        }
        utf8_arr=new char[res];
        WideCharToMultiByte(CP_UTF8,0,system_arr,-1,utf8_arr,res,nullptr,nullptr);

        r=std::string(utf8_arr);
      }while(false);

      if(utf8_arr!=nullptr){
        delete[] utf8_arr;
      }
      if(system_arr!=nullptr){
        LocalFree(system_arr);
      }

      return r;
    }

    std::string GetErrorString()noexcept{
      return GetErrorString(GetLastError());
    }

    std::string GetErrorStringWithErrorCode(DWORD error)noexcept{
      return GetErrorString(error)+" 错误码:"+std::to_string(error);
    }

    std::string GetErrorStringWithErrorCode()noexcept{
      return GetErrorStringWithErrorCode(GetLastError());
    }

#endif

  }

}



